<?php

namespace App\Kuafu\WaiMai\Channel;

use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\WaiMai\Enum\WaiMaiCodeEnum;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use App\Kuafu\WaiMai\Exceptions\WaiMaiException;
use App\Kuafu\WaiMai\Model\WaiMaiShopMappingModel;
use App\Kuafu\WaiMai\Service\WaiMaiShopService;

class BaseWaiMai
{
    private static $ins;
    private static $insExpiredAt;

    public function __construct()
    {

    }

    public static function getIns(int $sourceType, int $shopId, string $thirdShopId = '')
    {
        switch ($sourceType) {
            case CodeEnum::SOURCE_TYPE_ELM:
                $className = ElmWaiMai::class;
                break;
            case CodeEnum::SOURCE_TYPE_MT:
                $className = MtWaiMai::class;
                break;
            case CodeEnum::SOURCE_TYPE_DY:
                $className = DyWaiMai::class;
                break;
            default:
                throw new WaiMaiException(WaiMaiCodeEnum::ERR_SOURCE_TYPE);
        }

        if (!$thirdShopId) {

            // shopId转换thirdShopId
            $sourceTypeWaiMai = $sourceType;
            if ($sourceType == CodeEnum::SOURCE_TYPE_DY) {// 外卖订单抖音类型转化
                $sourceTypeWaiMai = WaiMaiDBEnum::SOURCE_TYPE_DOUYIN_WM;
            }
            $thirdShopId = WaiMaiShopService::getMappingCache($shopId, $sourceTypeWaiMai)['thirdShopId'] ?? '';
//            if (!$thirdShopId) {
//                throw new WaiMaiException(WaiMaiCodeEnum::ERR_SHOP_ID_NOT_BIND);
//            }
        }

        // 享元10分钟过期
        $insKey = $sourceType . '-' . $shopId;
        if ((self::$ins[$insKey] ?? null) instanceof $className && (static::$insExpiredAt[$insKey] ?? 0) - time() > 0) {
            return self::$ins[$insKey];
        }

        static::$insExpiredAt[$insKey] = time() + 600;

        return self::$ins[$insKey] = new $className($thirdShopId, $shopId);
    }


    /**
     * 接口返回通用处理
     * @param bool $status
     * @param string $code
     * @param string $msg
     * @param array $oriData
     * @return array
     */
    protected function returnFormatData(bool $status, string $code, string $msg, $oriData): array
    {
        if (is_object($oriData)) {
            $oriData = json_decode(json_encode($oriData), true);
        }

        return [
            'status'  => $status, // true: 接口成功 false: 接口失败
            'code'    => $code, // 错误码
            'msg'     => $msg,  // 错误信息
            'data'    => [],   // 多种支付渠道合并后的，固定通用返回字段
            'oriData' => $oriData, //
        ];
    }
}
